package com.lxk.aop;

import com.lxk.service.LoginService;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.result.CodeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JohnSoybean
 * @create 2020/3/19 15:34
 * @description 轻量级验证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = (String) request.getParameter("token");
        if(null==token) {
            throw new GlobalException(CodeMsg.NO_TOKEN);
        }
        Long id = loginService.authToken(token);
        if(null==id) {  //已过期或不存在
            throw new GlobalException(CodeMsg.INVALID_TOKEN);
        }
        request.setAttribute("userId", id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
